package com.wejoy.video.middle.station.data.service.workorder.impl;/**
 * @Author 张文杰
 * @PackageName video-middle-station
 * @Package com.wejoy.video.middle.station.data.service.workorder.impl
 * @Date 2022/11/30 5:06 PM
 * @Version 1.0
 */

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSONArray;
import com.wejoy.video.middle.station.data.domain.alarm.AlarmDetails;
import com.wejoy.video.middle.station.data.domain.detection.DetectionIntervar;
import com.wejoy.video.middle.station.data.domain.system.*;
import com.wejoy.video.middle.station.data.domain.workorder.OrderAlarmInfo;
import com.wejoy.video.middle.station.data.domain.workorder.OrderPhotoLib;
import com.wejoy.video.middle.station.data.domain.workorder.WorkOrderInfo;
import com.wejoy.video.middle.station.data.enums.dict.*;
import com.wejoy.video.middle.station.data.enums.file.EnumUpload;
import com.wejoy.video.middle.station.data.exception.BusinessException;
import com.wejoy.video.middle.station.data.service.alarm.IAlarmDetailsService;
import com.wejoy.video.middle.station.data.service.detection.IDetectionIntervarService;
import com.wejoy.video.middle.station.data.service.evs.IEvsHttpService;
import com.wejoy.video.middle.station.data.service.file.IFileService;
import com.wejoy.video.middle.station.data.service.system.*;
import com.wejoy.video.middle.station.data.service.wechat.IWeChatService;
import com.wejoy.video.middle.station.data.service.workorder.IEvsCallbackService;
import com.wejoy.video.middle.station.data.service.workorder.IOrderAlarmInfoService;
import com.wejoy.video.middle.station.data.service.workorder.IOrderPhotoLibService;
import com.wejoy.video.middle.station.data.service.workorder.IWorkOrderInfoService;
import com.wejoy.video.middle.station.data.util.DateUtils;
import com.wejoy.video.middle.station.data.util.StringUtils;
import com.wejoy.video.middle.station.data.util.WJAssert;
import com.wejoy.video.middle.station.data.vo.workorder.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * @BelongsProject: video-middle-station
 * @BelongsPackage: com.wejoy.video.middle.station.data.service.workorder.impl
 * @Author: zhangwenjie
 * @CreateTime: 2022-11-30  17:06
 * @Description: TODO
 * @Version: 1.0
 */
@Service
public class EvsCallbackServiceImpl implements IEvsCallbackService{
    private final static Logger LOGGER = LoggerFactory.getLogger(EvsCallbackServiceImpl.class);

    @Autowired
    private ISysNoticeService sysNoticeService;
    @Autowired
    private IWorkOrderInfoService workOrderInfoService;
    @Autowired
    private ISysDeptCameraService sysDeptCameraService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysDeptUserService sysDeptUserService;
    @Autowired
    private IOrderAlarmInfoService orderAlarmInfoService;
    @Autowired
    private IFileService fileService;
    @Autowired
    private IOrderPhotoLibService orderPhotoLibService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ISysBaseParamService baseParamService;
    @Autowired
    private IDetectionIntervarService detectionIntervarService;
    @Autowired
    private IEvsHttpService evsHttpService;
    @Autowired
    private ISysCarmeraService sysCarmeraService;
    @Autowired
    private IWeChatService weChatService;
    @Autowired
    private IEvsUserService evsUserService;
    @Autowired
    private IAlarmDetailsService alarmDetailsService;

    private static final int PAGE_SIZE = 100;
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void initWorkOrder(EvsCallbackVO callbackVo) {
        saveOrder(callbackVo);
    }

    @Override
    public void initWorkOrder(OrderCallBackVO callbackVo) {
        //点位和部门信息
        PointInfo pointInfo = callbackVo.getPointInfo();
        AnalysisResult analysisResult = callbackVo.getAnalysisResult();
        List<Event> events = analysisResult.getEvent();
        for (Event event : events) {
            //事件开始存入工单
            if(event.getEventStatus().equals(EnumEvsEventStatus.START.getCode())){
                SysCarmera carmera = sysCarmeraService.getOneById(pointInfo.getPointId());
                if(ObjectUtils.isEmpty(carmera)){
                    LOGGER.info("设备不存在，已拒绝，事件id：{},设备id：{}",event.getEventId(),pointInfo.getPointId());
                    return;
                }
                //生成工单
                AlarmDetails alarmDetails = new AlarmDetails();
                alarmDetails.setDeviceName(pointInfo.getPointName());
                if(!StringUtils.isEmpty(callbackVo.getAnalysisResult().getVideoUrl())){
                    alarmDetails.setVideoUrl(videoStorage(callbackVo.getAnalysisResult().getVideoUrl()));
                }
                //基本信息
                alarmDetails.setTriggerTime(new Date(event.getCaptureTime()));
                alarmDetails.setEventId(event.getEventId());
                alarmDetails.setOrderStatus(EnumYesNo.YES.getCode());
                alarmDetails.setBusinessScenario(event.getEventType());
                //工单告警信息
                String text = EnumWorkAlarmType.getText(event.getEventType());
                alarmDetails.setAlarmLocation(text);
                //点位相关信息
                alarmDetails.setDeviceId(pointInfo.getPointId());
                //部门信息
                alarmDetails.setDeptId(pointInfo.getDepartmentId());
                //取最后一个部门  X科技有限公司/研发部/研发一组 取研发一组
                String[] parts = pointInfo.getDepartmentPath().split("/");
                alarmDetails.setDeptName(pointInfo.getPointName());
                alarmDetails.setAffiliation(pointInfo.getDepartmentPath());
                //图片存储
                alarmDetails.setImageUrl(pictureStorage(event.getSnapshot().getUrl()));
                alarmDetails.setImageAttributeJson(JSONObject.toJSONString(callbackVo.getAnalysisResult()));
                //工单保存
                alarmDetailsService.save(alarmDetails,"EVS报警回调");
                //点位报警数量+1
                carmera.setAlarmsCount(carmera.getAlarmsCount()==null?1:carmera.getAlarmsCount()+1);
                carmera.setAlarmStatus(EnumYesNo.YES.getCode());
                sysCarmeraService.updateSelectiveById(carmera);
                //部门报警数量+1
                SysDept sysDept = sysDeptService.getOneById(pointInfo.getDepartmentId());
                sysDept.setAlarmsCount(sysDept.getAlarmsCount()==null?1:sysDept.getAlarmsCount()+1);
                sysDept.setIsAlarmStatus(true);
                sysDeptService.updateSelectiveById(sysDept);
                LOGGER.info("已发起工单，事件id：{}",event.getEventId());
            } else if(event.getEventStatus().equals(EnumEvsEventStatus.END.getCode())){
                //如果是事件结束，
                AlarmDetails alarmDetails = alarmDetailsService.getOneByEventId(event.getEventId());
                if(!ObjectUtils.isEmpty(alarmDetails)){
                    alarmDetails.setOrderStatus(EnumYesNo.NO.getCode());
                    alarmDetailsService.updateSelectiveById(alarmDetails);
                    //查询对应设备和部门的工单是否有报警进行中的
                    AlarmDetails alarmDetailsQuery = new AlarmDetails();
                    alarmDetailsQuery.setDeviceId(pointInfo.getPointId());
                    alarmDetailsQuery.setOrderStatus(EnumYesNo.NO.getCode());
                    int count = alarmDetailsService.getCount(alarmDetailsQuery);
                    if(count == 0){
                        SysCarmera carmera = sysCarmeraService.getOneById(pointInfo.getPointId());
                        if(!ObjectUtils.isEmpty(carmera)){
                            carmera.setAlarmStatus(EnumYesNo.NO.getCode());
                            sysCarmeraService.updateSelectiveById(carmera);
                        }
                    }
                    alarmDetailsQuery.setDeviceId(null);
                    alarmDetailsQuery.setDeptId(pointInfo.getDepartmentId());
                    if(count == 0){
                        SysDept sysDept = sysDeptService.getOneById(pointInfo.getDepartmentId());
                        if(!ObjectUtils.isEmpty(sysDept)){
                            sysDept.setIsAlarmStatus(false);
                            sysDeptService.updateSelectiveById(sysDept);
                        }
                    }
                }
                LOGGER.info("未找到工单。无法结束，事件id：{}",event.getEventId());
            }
        }
    }

    private int checkOrderEventById(Event event) {
        WorkOrderInfo workOrderInfo = new WorkOrderInfo();
        workOrderInfo.setEventId(event.getEventId());
        int count = workOrderInfoService.getCount(workOrderInfo);
        return count;
    }

    @Override
    public void pushPhoto(EvsCallbackVO callback) {
        WorkOrderInfo where = new WorkOrderInfo();
        where.setEventId(callback.getEventId());
        List<WorkOrderInfo> list = workOrderInfoService.getList(where);
        if(!CollectionUtils.isEmpty(list)){
            WorkOrderInfo info = list.get(0);
            OrderPhotoLib photoLib = new OrderPhotoLib();
            photoLib.setOrderId(info.getId());
            int count = orderPhotoLibService.getCount(photoLib);
            //图片小于9张就往里push
            OrderPhotoLib orderPhotoLib =null;
            if(count<9){
                orderPhotoLib = new OrderPhotoLib();
                orderPhotoLib.setOrderId(info.getId());
                orderPhotoLib.setCallBackStatus(callback.getEventStatus());
                String imageUrl = pictureStorage(callback.getObjectUrl());
                orderPhotoLib.setImageUrl(imageUrl);
                orderPhotoLib.setCreateTime(new Date(callback.getTimestamp()));
            }else if(count==9&&callback.getEventStatus().equals(EnumEvsEventStatus.END.getCode())){
                //最后一张图必须是end +前面9张=10张
                orderPhotoLib = new OrderPhotoLib();
                orderPhotoLib.setOrderId(info.getId());
                orderPhotoLib.setCallBackStatus(callback.getEventStatus());
                String imageUrl = pictureStorage(callback.getObjectUrl());
                orderPhotoLib.setImageUrl(imageUrl);
                orderPhotoLib.setCreateTime(new Date(callback.getTimestamp()));
            }
            if(!ObjectUtils.isEmpty(orderPhotoLib)){
                orderPhotoLib.setImageAttributeJson(JSONObject.toJSONString(callback.getAnalysisResult()));
                orderPhotoLibService.save(orderPhotoLib,"");
            }
        }
    }

    /**
     * 保存工单基本信息
     */
    private void saveOrder(EvsCallbackVO callbackVo){
        WorkOrderInfo workOrderInfoDB = new WorkOrderInfo();
        //工单基本信息存储
        workOrderInfoDB.setTriggerTime(new Date(callbackVo.getTimestamp()));
        workOrderInfoDB.setEventId(callbackVo.getEventId());
        workOrderInfoDB.setOrderStatus(EnumWorkOrderStatus.AGENCY.getCode());
        workOrderInfoDB.setBusinessScenario(callbackVo.getEventType());
        //工单告警信息存储
        OrderAlarmInfo alarmInfo = getAlarmInfo(callbackVo.getEventType());
        workOrderInfoDB.setAlarmLocation(alarmInfo.getName());
        workOrderInfoDB.setMainTypeId(alarmInfo.getMainTypeId());
        workOrderInfoDB.setMainTypeName(alarmInfo.getMainTypeName());
        workOrderInfoDB.setMinorTypeId(alarmInfo.getMinorTypeId());
        workOrderInfoDB.setMinorTypeName(alarmInfo.getMinorTypeName());
        //摄像头相关信息存储
        SysDeptCamera sysDeptCamera = getSysDeptCameraBydeviceId(callbackVo.getDeviceId());
        workOrderInfoDB.setDeptId(sysDeptCamera.getDepId());
        workOrderInfoDB.setSpaceType(sysDeptCamera.getSpaceType());
        workOrderInfoDB.setDeptName(sysDeptCamera.getDepName());
        workOrderInfoDB.setDeviceId(sysDeptCamera.getDeviceId());
        //工单部门相关信息及负责人存储
        SysDept sysDept = getDept(sysDeptCamera.getDepId());
        sysDept.setAlarmsCount(sysDept.getAlarmsCount()==null?1:sysDept.getAlarmsCount()+1);
        workOrderInfoDB.setArea(sysDept.getArea());
//        workOrderInfoDB.setManagerUserId(sysDept.getUserId());
//        workOrderInfoDB.setManagerUserName(sysDept.getUserName());
//        SysUser sysUser = sysUserService.getOneById(sysDept.getUserId());
//        workOrderInfoDB.setManagerUserPhone(Long.valueOf(sysUser.getPhone()));
        workOrderInfoDB.setAffiliation(getAffiliation(sysDept.getId()));
        //调度中心信息
//        SysDept dispatchCenterDept = getDispatchCenterDept(sysDept);
//        workOrderInfoDB.setDispatchCenterId(dispatchCenterDept.getId());
//        workOrderInfoDB.setDispatchCenterName(dispatchCenterDept.getName());
        Boolean checkOrder = checkOrder(workOrderInfoDB.getDeviceId(), workOrderInfoDB.getDeptId(), workOrderInfoDB.getBusinessScenario());
        if(checkOrder){
            throw new BusinessException("重复工单");
        }
        //图片存储
        workOrderInfoDB.setImageUrl(pictureStorage(callbackVo.getObjectUrl()));
        workOrderInfoDB.setImageAttributeJson(JSONObject.toJSONString(callbackVo.getAnalysisResult()));
        //工单保存
        workOrderInfoService.save(workOrderInfoDB,"视频中台");
        OrderPhotoLib orderPhotoLib = new OrderPhotoLib();
        orderPhotoLib.setOrderId(workOrderInfoDB.getId());
        orderPhotoLib.setCallBackStatus(callbackVo.getEventStatus());
        orderPhotoLib.setImageUrl(workOrderInfoDB.getImageUrl());
        orderPhotoLib.setCreateTime(new Date(callbackVo.getTimestamp()));
        orderPhotoLib.setImageAttributeJson(JSONObject.toJSONString(callbackVo.getAnalysisResult()));
        orderPhotoLibService.save(orderPhotoLib,"");
        redisTemplate.opsForList().rightPush(EnumBigScreen.HF_SCREEN.getValue(),JSONObject.toJSONString(workOrderInfoDB));
        redisTemplate.opsForList().rightPush(EnumBigScreen.SZ_SCREEN.getValue(),JSONObject.toJSONString(workOrderInfoDB));
        sysDeptService.updateSelectiveById(sysDept);
        //下发通知到机构用户
        notify(workOrderInfoDB,sysDept);
        //摄像头报警数+1
        sysDeptCameraService.save(sysDeptCamera,"EVS");
    }

    private Boolean checkOrder(Long deviceId,Long deptId,String businessScenario){
        WorkOrderInfo workOrderInfo = new WorkOrderInfo();
        workOrderInfo.setDeviceId(deviceId);
        workOrderInfo.setDeptId(deptId);
        workOrderInfo.setBusinessScenario(businessScenario);
        workOrderInfo.setPageNo(1);
        workOrderInfo.setPageSize(1);
        List<WorkOrderInfo> list = workOrderInfoService.getPageList(workOrderInfo);
        if(!CollectionUtils.isEmpty(list)){
            WorkOrderInfo orderInfo = list.get(0);
            SysBaseParam interval = baseParamService.getOneByUniCode("SYSTEM_CHECK_ORDER");
            if(ObjectUtils.isEmpty(interval)){
                return false;
            }
            if(DateUtils.minusTime(orderInfo.getCreateTime(),new Date(), Calendar.MINUTE)<= Integer.valueOf(interval.getValue())){
                return true;
            }
        }
        return false;
    }

    /**
     * 是否达到间隔时间
     * @param deviceId
     * @param deptId
     * @param businessScenario
     * @return
     */
    private Boolean checkOrderInterval(Long deviceId,Long deptId,String businessScenario){
        WorkOrderInfo workOrderInfo = new WorkOrderInfo();
        workOrderInfo.setDeviceId(deviceId);
        workOrderInfo.setDeptId(deptId);
        workOrderInfo.setBusinessScenario(businessScenario);
        workOrderInfo.setPageNo(1);
        workOrderInfo.setPageSize(1);
        List<WorkOrderInfo> list = workOrderInfoService.getPageList(workOrderInfo);
        if(!CollectionUtils.isEmpty(list)){
            WorkOrderInfo orderInfo = list.get(0);
            DetectionIntervar detectionIntervar = detectionIntervarService.getOneByType(businessScenario);
            if(ObjectUtils.isEmpty(detectionIntervar)){
                return false;
            }
            if(DateUtils.minusTime(orderInfo.getCreateTime(),new Date(), Calendar.MINUTE)<= Integer.valueOf(detectionIntervar.getIntervalTime())){
                return true;
            }
        }
        return false;
    }

    /**
     * 图片存储
     */
    private String pictureStorage(String imgUrl){
        WJAssert.notBlank(imgUrl,"imgUrl cannot be empty");
        byte[] fileStream = getFileStream(imgUrl);
        if(ObjectUtils.isEmpty(fileStream)){
            LOGGER.error("图片存储失败");
            return imgUrl;
        }
        return fileService.upload(EnumUpload.RES_PHOTO_LIB,fileStream).getKey();
    }

    /**
     * 视频存储
     */
    private String videoStorage(String videoUrl){
        WJAssert.notBlank(videoUrl,"videoUrl cannot be empty");
        byte[] fileStream = getFileStream(videoUrl);
        if(ObjectUtils.isEmpty(fileStream)){
            LOGGER.error("图片存储失败");
            return videoUrl;
        }
        return fileService.upload(EnumUpload.ORDER_VIDEO,fileStream).getKey();
    }

    /**
     * 拼接所属机构  1级/2级/3级/4级
     * @param deptId
     * @return
     */
    private String getAffiliation(Long deptId){
        List<SysDept> list = sysDeptService.getList(new SysDept());
        Optional<SysDept> deptOptional = list.stream().filter(item -> item.getId().equals(deptId)).findFirst();
        if (!deptOptional.isPresent()) {
            return null;
        }
//        return buildDepName(deptOptional.get().getParentId(), list, deptOptional.get().getShowName());
        return null;
    }

    private String buildDepName(String parentId, List<SysDept> deptList, String affiliationName) {
        Optional<SysDept> sysDeptOptional = deptList.stream().filter(item -> item.getId().toString().equals(parentId)).findFirst();
        if (sysDeptOptional.isPresent()) {
            affiliationName = sysDeptOptional.get().getName()+"/"+affiliationName;
//            return buildDepName(sysDeptOptional.get().getParentId(), deptList, affiliationName);
        }
        return affiliationName;
    }

    /**
     * 得到文件流
     * @param url  网络图片URL地址
     * @return
     */
    private static byte[] getFileStream(String url){
        LOGGER.info("Attempting to fetch image from URL: " + url);
        try {
            URL httpUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(10 * 1000); // 10秒超时
            int responseCode = conn.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                LOGGER.error("Failed to fetch image, response code: " + responseCode);
                return null;
            }
            InputStream inStream = conn.getInputStream(); // 获取输入流
            if (inStream == null) {
                LOGGER.error("Failed to get InputStream from URL: " + url);
            }
            byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
            return btImg;
        } catch (Exception e) {
            LOGGER.error("Error while fetching image: " + e.getMessage(), e);
            LOGGER.error("Error while fetching image from URL: " + url, e);
        }
        return null;
    }

    /**
     * 从输入流中获取数据
     * @param inStream 输入流
     * @return
     * @throws Exception
     */
    private static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len=inStream.read(buffer)) != -1 ){
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }



    /**
     * 告警所属部门
     * @param depId
     * @return
     */
    private SysDept getDept(Long depId){
        return sysDeptService.getOneById(depId);
    }

    /**
     * 告警所属调度中心-根据部门查询
     * @param sysDept
     * @return
     */
//    private SysDept getDispatchCenterDept(SysDept sysDept){
//        return sysDeptService.superiorDispatchCenter(sysDept);
//    }

    /**
     * 获取告警信息
     * @param eventType
     */
    private OrderAlarmInfo getAlarmInfo(String eventType) {
        WJAssert.notBlank(eventType,"回调告警类型为空");
        OrderAlarmInfo where = new OrderAlarmInfo();
        where.setCallBackName(eventType);
        List<OrderAlarmInfo> list = orderAlarmInfoService.getList(where);
        if(CollectionUtils.isEmpty(list)){
            throw new BusinessException("No such EventType");
        }
        OrderAlarmInfo orderAlarmInfo = list.get(0);
        if(ObjectUtils.isEmpty(orderAlarmInfo)){
            throw new BusinessException("No such EventType");
        }
        return orderAlarmInfo;
    }

    /**
     * 根据设备名称获取相关摄像头-部门信息
     * @param deviceName
     * @return
     */
    private SysDeptCamera getSysDeptCamera(String deviceName) {
        WJAssert.notBlank(deviceName,"设备名称为空");
        String name = StringUtils.deleteWhitespace(deviceName);
        SysDeptCamera sysDeptCamera = sysDeptCameraService.getOneByName(name);
        if(ObjectUtils.isEmpty(sysDeptCamera)){
            throw new BusinessException("找不到设备名对应部门");
        }
        sysDeptCamera.setAlarmsCount(sysDeptCamera.getAlarmsCount()+1);
        return sysDeptCamera;
    }

    /**
     * 根据通道id查找设备
     * @param deviceId
     * @return
     */
    private SysDeptCamera getSysDeptCameraBydeviceId(Long deviceId) {
        SysDeptCamera sysDeptCameraEq = new SysDeptCamera();
        sysDeptCameraEq.setDeviceId(deviceId);
        List<SysDeptCamera> list = sysDeptCameraService.getList(sysDeptCameraEq);
        SysDeptCamera sysDeptCamera =null;
        if(!CollectionUtils.isEmpty(list)){
            sysDeptCamera=list.get(0);
        }
        if(ObjectUtils.isEmpty(sysDeptCamera)){
            throw new BusinessException("找不到对应部门");
        }
        sysDeptCamera.setAlarmsCount(sysDeptCamera.getAlarmsCount()+1);
        return sysDeptCamera;
    }

    /**
     * 下发通知到所属机构下所有人员
     * @param workOrderInfoDB
     * @param sysDept
     */
    private void notify(WorkOrderInfo workOrderInfoDB, SysDept sysDept) {
        SysDeptUser sysDeptUserEQ = new SysDeptUser();
        sysDeptUserEQ.setDeptId(sysDept.getId());
        sysDeptUserService.getList(sysDeptUserEQ).parallelStream().forEach(item ->{
            if(!item.getUserId().equals(sysDept.getUserId())){
                SysNotice sysNotice = new SysNotice();
                sysNotice.setTitle(EnumNoticeType.NEW_ORDERS_NOTICE.getText());
                sysNotice.setRemindType(EnumNoticePopUpsType.WARNING_POPUPS.getCode());
                sysNotice.setToId(item.getUserId());
                sysNotice.setOrderId(workOrderInfoDB.getId());
                sysNotice.setIsRead(EnumReadNoticeType.HAVE_READ.getCode());
                sysNotice.setType(EnumNoticeType.NEW_ORDERS_NOTICE.getCode());
                sysNotice.setIsRemind(EnumNoticeRemindtype.NOT_REMINDED.getCode());
                sysNotice.setContent(workOrderInfoDB.getDeptName()+"-"+ workOrderInfoDB.getAlarmLocation());
                sysNoticeService.save(sysNotice,"系统通知");
            }
        });
    }

    /**
     * 下发通知到所属机构下所有人员
     * @param workOrderInfoDB
     * @param sysDept
     */
    @Async
    protected void notifyDeptAllDept(WorkOrderInfo workOrderInfoDB, SysDept sysDept) {
        List<Long> userIds = new ArrayList<>();
        getDeptAllusers(sysDept.getId(), userIds,1);
        if(!CollectionUtils.isEmpty(userIds)){
            userIds.forEach(item->{
                if(!sysDept.getUserId().contains(item.toString())){
                    SysNotice sysNotice = new SysNotice();
                    sysNotice.setTitle(EnumNoticeType.NEW_ORDERS_NOTICE.getText());
                    sysNotice.setRemindType(EnumNoticePopUpsType.WARNING_POPUPS.getCode());
                    sysNotice.setToId(item);
                    sysNotice.setOrderId(workOrderInfoDB.getId());
                    sysNotice.setIsRead(EnumReadNoticeType.HAVE_READ.getCode());
                    sysNotice.setType(EnumNoticeType.NEW_ORDERS_NOTICE.getCode());
                    sysNotice.setIsRemind(EnumNoticeRemindtype.NOT_REMINDED.getCode());
                    sysNotice.setContent(workOrderInfoDB.getDeptName()+"-"+ workOrderInfoDB.getAlarmLocation());
                    sysNoticeService.save(sysNotice,"系统通知");
                }
            });
        }
        senWechatMessage(userIds,workOrderInfoDB.getDeptName());
    }

    /**
     * 发送微信消息
     * @param uId
     */
    private void senWechatMessage( List<Long> uId,String deptName) {
        List<String> userIds = new ArrayList<>();
        uId.forEach(item->{
            EvsUser evsUser = new EvsUser();
            evsUser.setUserId(item);
            List<EvsUser> list = evsUserService.getList(evsUser);
            if(!CollectionUtils.isEmpty(list)){
                if(!StringUtils.isEmpty(list.get(0).getWechatId())){
                    userIds.add(list.get(0).getWechatId());
                }
            }
        });
        if(!CollectionUtils.isEmpty(userIds)){
            weChatService.sendMessage(userIds,deptName);
        }
    }


    private List<Long> getDeptAllusers(Long deptId,List<Long> userIds,int pageNo){
        com.alibaba.fastjson2.JSONObject users = evsHttpService.getUsers(deptId.intValue(), 1, PAGE_SIZE, "", "", evsHttpService.getToken());
        Long totalCount = users.getLong("totalCount");
        JSONArray data = users.getJSONArray("data");
        for (int i = 0; i < data.size(); i++) {
            userIds.add(data.getJSONObject(i).getLong("userId"));
        }
        if(totalCount>(PAGE_SIZE*pageNo)){
            return getDeptAllusers(deptId,userIds,pageNo+1);
        }
        return userIds;
    }



}
